
//------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using Apps.Models;
using Apps.Common;
using Microsoft.Practices.Unity;
using System.Transactions;
using Apps.BLL.Core;
using Apps.Locale;
using LinqToExcel;
using System.IO;
using System.Text;
using System.Linq.Expressions;
using Apps.IDAL.RC;
using Apps.Models.RC;
using Apps.IBLL.RC; 

namespace Apps.BLL.RC
{
	public partial class RC_INBLL: Virtual_RC_INBLL,IRC_INBLL
	{
        

	}
	public class Virtual_RC_INBLL
	{
        [Dependency]
        public IRC_INRepository m_Rep { get; set; }

        public List<V_RC_INModel> GetVList(ref GridPager pager, Expression<Func<V_RC_IN, bool>> whereLambda)
        {
            using (DBContainer db = new DBContainer())
            {
                var queryData = db.V_RC_IN.Where(whereLambda);
                pager.totalRows = queryData.Count();
                queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                return TransHelper.TransExpList<V_RC_IN, V_RC_INModel>(queryData.ToList());
            }
        }

        public List<VV_RC_PROCESSModel> GetVPROCESSList(ref GridPager pager, Expression<Func<V_RC_PROCESS, bool>> whereLambda)
        {
            using (DBContainer db = new DBContainer())
            {
                var queryData = db.V_RC_PROCESS.Where(whereLambda);
                pager.totalRows = queryData.Count();
                queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                //return TransHelper.TransExpList<V_RC_PROCESS, V_RC_PROCESSModel>(queryData.ToList());
                return CreateModelList(ref queryData,db);
            }
        }

        public virtual List<VV_RC_PROCESSModel> CreateModelList(ref IQueryable<V_RC_PROCESS> queryData, DBContainer db)
        {
            try
            {
                Nullable<int> tmp_OPERATION_MODE = null;
                Nullable<System.DateTime> tmp_MATCH_TIME = null;
                List<VV_RC_PROCESSModel> modelList = (from r in queryData
                                                      join i in db.V_RC_IN  on r.PROCESS_ID equals i.PROCESS_ID into tmpRcIn
                                                      from f in tmpRcIn.DefaultIfEmpty()
                                                      select new VV_RC_PROCESSModel
                                                      {
                                                          PROCESS_ID = r.PROCESS_ID,
                                                          DETAIL_ID = r.DETAIL_ID,
                                                          CAR_ID = r.CAR_ID,
                                                          LPR = r.LPR,
                                                          RFID = r.RFID,
                                                          BATCH_CODE = r.BATCH_CODE,
                                                          MINE_ID = r.MINE_ID,
                                                          MINE_NAME = r.MINE_NAME,
                                                          MINE_CODE = r.MINE_CODE,
                                                          MATERIEL_ID = r.MATERIEL_ID,
                                                          MATERIEL_NAME = r.MATERIEL_NAME,
                                                          MATERIEL_CODE = r.MATERIEL_CODE,
                                                          TEMPLATE_ID = r.TEMPLATE_ID,
                                                          SUPPLIER_ID = r.SUPPLIER_ID,
                                                          SUPPLIER_NAME = r.SUPPLIER_NAME,
                                                          SUPPLIER_CODE = r.SUPPLIER_CODE,
                                                          TRANSPORT_ID = r.TRANSPORT_ID,
                                                          TRANSPORT_NAME = r.TRANSPORT_NAME,
                                                          TRANSPORT_CODE = r.TRANSPORT_CODE,
                                                          IS_COAL = r.IS_COAL,
                                                          PLAN_DATE = r.PLAN_DATE,
                                                          STATISTICS = r.STATISTICS,
                                                          STATUS = r.STATUS,
                                                          BILL_WEIGHT = r.BILL_WEIGHT,
                                                          OVERLOAD_RADOM = r.OVERLOAD_RADOM,
                                                          UPDATE_TIME = r.UPDATE_TIME,
                                                          OPERATION_MODE = f == null ? tmp_OPERATION_MODE : f.OPERATION_MODE,
                                                          MATCH_USER_ID = ((f == null) ? null : f.MATCH_USER_ID),
                                                          MATCH_USER_NAME = ((f == null) ? null : f.MATCH_USER_NAME),
                                                          MATCH_TIME = f == null ? tmp_MATCH_TIME : f.MATCH_TIME,

                                                      }).ToList();

                return modelList;
            }
            catch (Exception ex)
            {
                ExceptionHander.WriteException(ex);
                return null;
            }
        }

        public List<V_RC_INModel> GetVNoJLList(string carid,string recordid)
        {
            using (DBContainer db = new DBContainer())
            {
                var queryData = (from i in db.V_RC_IN
                            join w in db.RC_WEIGHING on i.PROCESS_ID equals w.PROCESS_ID into wt
                            from p1 in wt.DefaultIfEmpty()
                            join r in (from r0 in db.RC_WEIGHING_RECORD where string.IsNullOrEmpty(recordid) || r0.RECORD_ID != recordid select r0 )
                            on i.PROCESS_ID equals r.PROCESS_ID into wr
                            from p2 in wr.DefaultIfEmpty()
                            where i.CAR_ID == carid && i.IS_COAL == 1 &&  p1 == null && p2 == null 
                            orderby i.BATCH_CODE descending
                            select i ); 
                return TransHelper.TransExpList<V_RC_IN, V_RC_INModel>(queryData.ToList());
            }
        }

        public List<V_RC_PROCESSModel> GetVPROCESS_JLList(string carid, string recordid)
        {
            using (DBContainer db = new DBContainer())
            {
                var queryData = (from i in db.V_RC_PROCESS
                                 join w in db.RC_WEIGHING on i.PROCESS_ID equals w.PROCESS_ID into wt
                                 from p1 in wt.DefaultIfEmpty()
                                 join r in db.RC_WEIGHING_RECORD on i.PROCESS_ID equals r.PROCESS_ID into wr
                                 from p2 in wr.DefaultIfEmpty()
                                 where i.CAR_ID == carid && i.IS_COAL == true && p1 == null && !(new int?[] { 2, 3 }).Contains(p2.APPROVAL_STATUS) && (string.IsNullOrEmpty(recordid) && p2.RECORD_ID != recordid)
                                 orderby i.BATCH_CODE descending
                                 select i).Distinct();
                return TransHelper.TransExpList<V_RC_PROCESS, V_RC_PROCESSModel>(queryData.ToList());
            }
        }

        public List<V_RC_PROCESSModel> GetVPROCESS_JLList(string carid)
        {
            using (DBContainer db = new DBContainer())
            {
                var queryData = (from i in db.V_RC_PROCESS 
                                 where i.CAR_ID == carid && i.IS_COAL == true   
                                 select i);
                return TransHelper.TransExpList<V_RC_PROCESS, V_RC_PROCESSModel>(queryData.ToList());
            }
        }

        public V_RC_PROCESSModel GetVPROCESSItem(Expression<Func<V_RC_PROCESS, bool>> whereLambda)
        {
            using (DBContainer db = new DBContainer())
            {
                var entity = db.V_RC_PROCESS.SingleOrDefault(whereLambda);
                return TransHelper.TransExp<V_RC_PROCESS, V_RC_PROCESSModel>(entity);
            }
        }

        public List<V_RC_INModel> GetVModifyJLList(string carid, string recordid)
        {
            using (DBContainer db = new DBContainer())
            {
                var queryData = (from i in db.V_RC_IN
                                 join w in db.RC_WEIGHING on i.PROCESS_ID equals w.PROCESS_ID   
                                 join r in (from r0 in db.RC_WEIGHING_RECORD where r0.RECORD_TYPE == true && (string.IsNullOrEmpty(recordid) || r0.RECORD_ID != recordid) select r0)
                                 on i.PROCESS_ID equals r.PROCESS_ID into wr
                                 from p2 in wr.DefaultIfEmpty()
                                 where i.CAR_ID == carid && i.IS_COAL == 1 && w.UPLOAD_STATUS == false && p2 == null
                                 orderby i.BATCH_CODE descending
                                 select i);
                return TransHelper.TransExpList<V_RC_IN, V_RC_INModel>(queryData.ToList());
            }
        }

        public List<V_RC_PROCESSModel> GetVPROCESSModifyJLList(string carid, string recordid)
        {
            using (DBContainer db = new DBContainer())
            {
                var queryData = (from i in db.V_RC_PROCESS
                                 join w in db.RC_WEIGHING on i.PROCESS_ID equals w.PROCESS_ID
                                 join r in (from r0 in db.RC_WEIGHING_RECORD where r0.RECORD_TYPE == true && (string.IsNullOrEmpty(recordid) || r0.RECORD_ID != recordid) select r0)
                                 on i.PROCESS_ID equals r.PROCESS_ID into wr
                                 from p2 in wr.DefaultIfEmpty()
                                 where i.CAR_ID == carid && i.IS_COAL == true && w.UPLOAD_STATUS == false && p2 == null
                                 orderby i.BATCH_CODE descending
                                 select i);
                return TransHelper.TransExpList<V_RC_PROCESS, V_RC_PROCESSModel>(queryData.ToList());
            }
        }


        public V_RC_INModel GetVItem(Expression<Func<V_RC_IN, bool>> whereLambda)
        {
            using (DBContainer db = new DBContainer())
            {
                var entity = db.V_RC_IN.SingleOrDefault(whereLambda); 
                return TransHelper.TransExp<V_RC_IN, V_RC_INModel>(entity);
            }
        }

        public virtual List<RC_INModel> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<RC_IN> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(
								a=>a.IN_ID.Contains(queryStr)
								|| a.PROCESS_ID.Contains(queryStr)
								|| a.NODE_ID.Contains(queryStr)
								
								|| a.MATCH_USER_ID.Contains(queryStr)
								
								);
            }
            else
            {
                queryData = m_Rep.GetList();
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }
		 
		public virtual List<RC_INModel> GetPagerList(ref GridPager pager, Expression<Func<RC_IN, bool>> whereLambda )
        {

            IQueryable<RC_IN> queryData = m_Rep.GetList(whereLambda); 
             
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

		public virtual List<RC_INModel> GetList(Expression<Func<RC_IN, bool>> whereLambda )
        {

            IQueryable<RC_IN> queryData = m_Rep.GetList(whereLambda); 
       
            return CreateModelList(ref queryData);
        }

		public virtual List<RC_INModel> GetListByParentId(ref GridPager pager, string queryStr,object parentId)
        {
			return new List<RC_INModel>();
		}

        public virtual List<RC_INModel> CreateModelList(ref IQueryable<RC_IN> queryData)
        {

            List<RC_INModel> modelList = (from r in queryData
                                              select new RC_INModel
                                              {
													IN_ID = r.IN_ID,
													PROCESS_ID = r.PROCESS_ID,
													NODE_ID = r.NODE_ID,
													OPERATION_MODE = r.OPERATION_MODE,
													MATCH_USER_ID = r.MATCH_USER_ID,
													MATCH_TIME = r.MATCH_TIME,
          
                                              }).ToList();

            return modelList;
        }

        public virtual bool Create(ref ValidationErrors errors, RC_INModel model)
        {
            try
            {
                RC_IN entity = m_Rep.GetById(model.IN_ID);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new RC_IN();
               				entity.IN_ID = model.IN_ID;
				entity.PROCESS_ID = model.PROCESS_ID;
				entity.NODE_ID = model.NODE_ID;
				entity.OPERATION_MODE = model.OPERATION_MODE;
				entity.MATCH_USER_ID = model.MATCH_USER_ID;
				entity.MATCH_TIME = model.MATCH_TIME;
  

                if (m_Rep.Create(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

		
		 public virtual bool Deletes(ref ValidationErrors errors,Expression<Func<RC_IN, bool>> whereLambda)
         {
		        try
				{
					using (DBContainer db = new DBContainer())
					{
				
							foreach (var entity in db.RC_IN.Where(whereLambda))
							{
								db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
							}

							if(db.SaveChanges()>0)
							{
								return true;
							}
							else
							{
								return false;
							}
			
					}
				}
				catch (Exception ex)
				{
					errors.Add(ex.Message);
					ExceptionHander.WriteException(ex);
					return false;
				}
        }

         public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                if (m_Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

		
       

        public virtual bool Edit(ref ValidationErrors errors, RC_INModel model)
        {
            try
            {
                RC_IN entity = m_Rep.GetById(model.IN_ID);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                              				entity.IN_ID = model.IN_ID;
				entity.PROCESS_ID = model.PROCESS_ID;
				entity.NODE_ID = model.NODE_ID;
				entity.OPERATION_MODE = model.OPERATION_MODE;
				entity.MATCH_USER_ID = model.MATCH_USER_ID;
				entity.MATCH_TIME = model.MATCH_TIME;
 


                if (m_Rep.Edit(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

      

        public virtual RC_INModel GetById(object id)
        {
            if (IsExists(id))
            {
                RC_IN entity = m_Rep.GetById(id);
                RC_INModel model = new RC_INModel();
                              				model.IN_ID = entity.IN_ID;
				model.PROCESS_ID = entity.PROCESS_ID;
				model.NODE_ID = entity.NODE_ID;
				model.OPERATION_MODE = entity.OPERATION_MODE;
				model.MATCH_USER_ID = entity.MATCH_USER_ID;
				model.MATCH_TIME = entity.MATCH_TIME;
 
                return model;
            }
            else
            {
                return null;
            }
        }

		public virtual RC_INModel GetItem(Expression<Func<RC_IN, bool>> whereLambda)
        {
 
                RC_IN entity = m_Rep.GetItem(whereLambda);
                if (entity == null) return null;

                RC_INModel model = new RC_INModel();
                              				model.IN_ID = entity.IN_ID;
				model.PROCESS_ID = entity.PROCESS_ID;
				model.NODE_ID = entity.NODE_ID;
				model.OPERATION_MODE = entity.OPERATION_MODE;
				model.MATCH_USER_ID = entity.MATCH_USER_ID;
				model.MATCH_TIME = entity.MATCH_TIME;
 
                return model; 
        }


		 /// <summary>
        /// 校验Excel数据,这个方法一般用于重写校验逻辑
        /// </summary>
        public virtual bool CheckImportData(string fileName, List<RC_INModel> list,ref ValidationErrors errors )
        {
          
            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
			 				 excelFile.AddMapping<RC_INModel>(x => x.IN_ID, "IN_ID");
				 excelFile.AddMapping<RC_INModel>(x => x.PROCESS_ID, "PROCESS_ID");
				 excelFile.AddMapping<RC_INModel>(x => x.NODE_ID, "NODE_ID");
				 excelFile.AddMapping<RC_INModel>(x => x.OPERATION_MODE, "OPERATION_MODE");
				 excelFile.AddMapping<RC_INModel>(x => x.MATCH_USER_ID, "MATCH_USER_ID");
				 excelFile.AddMapping<RC_INModel>(x => x.MATCH_TIME, "MATCH_TIME");
 
            //SheetName
            var excelContent = excelFile.Worksheet<RC_INModel>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new RC_INModel();
						 				  entity.IN_ID = row.IN_ID;
				  entity.PROCESS_ID = row.PROCESS_ID;
				  entity.NODE_ID = row.NODE_ID;
				  entity.OPERATION_MODE = row.OPERATION_MODE;
				  entity.MATCH_USER_ID = row.MATCH_USER_ID;
				  entity.MATCH_TIME = row.MATCH_TIME;
 
                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable<RC_INModel> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        RC_IN entity = new RC_IN();
                       						entity.IN_ID = model.IN_ID;
						entity.PROCESS_ID = model.PROCESS_ID;
						entity.NODE_ID = model.NODE_ID;
						entity.OPERATION_MODE = model.OPERATION_MODE;
						entity.MATCH_USER_ID = model.MATCH_USER_ID;
						entity.MATCH_TIME = model.MATCH_TIME;
 
                        db.RC_IN.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }


        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }
		  public void Dispose()
        { 
            
        }

	}
}
